package com.doubao.wechat.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Feign 请求拦截器配置
 * 将表单参数转换为 JSON 格式
 */
@Configuration
@Slf4j
public class FeignInterceptorConfig {

    @Bean
    public RequestInterceptor jsonRequestInterceptor() {
        return new RequestInterceptor() {
            private final ObjectMapper objectMapper = new ObjectMapper();

            @Override
            public void apply(RequestTemplate template) {
                log.info("Feign拦截器触发 - URL: {}, Method: {}", template.url(), template.method());

                // 只处理 POST 请求到 /wechat/bind 的情况
                // 注意：URL 可能包含查询参数，所以用 contains 判断
                if ("POST".equals(template.method()) &&
                        (template.url().contains("/wechat/bind") || template.path().contains("/wechat/bind"))) {

                    log.info("匹配到需要转换的请求");

                    // 获取查询参数
                    Map<String, Collection<String>> queries = template.queries();
                    log.info("查询参数: {}", queries);

                    if (!queries.isEmpty()) {
                        Map<String, Object> jsonBody = new HashMap<>();

                        // 将查询参数转换为 JSON body
                        queries.forEach((key, values) -> {
                            if (values != null && !values.isEmpty()) {
                                String value = values.iterator().next();
                                // 处理数字类型
                                if ("userId".equals(key)) {
                                    jsonBody.put(key, Long.parseLong(value));
                                } else {
                                    jsonBody.put(key, value);
                                }
                            }
                        });

                        try {
                            // 设置 JSON 请求体
                            String jsonString = objectMapper.writeValueAsString(jsonBody);
                            log.info("转换后的JSON: {}", jsonString);

                            template.body(jsonString);

                            // 清除查询参数
                            Set<String> keys = new HashSet<>(template.queries().keySet());
                            for (String key : keys) {
                                template.query(key, (String) null);
                            }

                            // 设置 Content-Type
                            template.header("Content-Type", "application/json;charset=UTF-8");
                            log.info("设置Content-Type为: application/json;charset=UTF-8");

                            // 打印最终的请求信息
                            log.info("最终请求 - URL: {}, Body: {}", template.url(), jsonString);
                        } catch (Exception e) {
                            log.error("转换 JSON 失败", e);
                            throw new RuntimeException("转换 JSON 失败", e);
                        }
                    } else {
                        log.warn("没有查询参数需要转换");
                    }
                } else {
                    log.debug("不匹配转换条件 - URL: {}, Method: {}", template.url(), template.method());
                }
            }
        };
    }
}